package com.hs.sfzy.controller;

import com.hs.sfzy.util.COSUtil;
import com.hs.sfzy.util.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName FileController
 * @Description TODO
 * @Author QinKunPeng
 * @Date 2024年10月23日 14:07
 * @Version 1.0
 */
@RestController
public class FileController {
    @PostMapping("/upload")
    public Object upload(MultipartFile file) throws IOException, InterruptedException {
        if (file == null) {
            return Result.error("未上传图片");
        }

        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-", "")
                + "-" + originalFilename;


        TransferManager transferManager = COSUtil.createTransferManager();
        String bucketName = "img-1307462045";
        String key = "sfzy/" + fileName;
        ObjectMetadata objectMetadata = new ObjectMetadata();

        InputStream inputStream = file.getInputStream();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);

        Upload upload = transferManager.upload(putObjectRequest);
        UploadResult uploadResult = upload.waitForUploadResult();
        COSUtil.shutdownTransferManager(transferManager);

        return Result.success(fileName);
    }


    @GetMapping("/downLoad")
    public Object getFile(String filename, HttpServletResponse response) throws IOException {
        if (filename == null || "".equals(filename)){
            return Result.error("未找到图片");
        }else{
            COSClient cosClient = COSUtil.createCOSClient();
            String bucketName = "img-1307462045";
            String key = "sfzy/" + filename;
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            COSObject object = cosClient.getObject(getObjectRequest);
            COSObjectInputStream objectContent = object.getObjectContent();
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(objectContent);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                outputStream.write(bytes, 0, len);
            }
            return Result.success();
        }
    }
}
